package buscador;

import buscador.resources.cargando;
import directoryPath.CustomizedDirectory;
import indexPack.*;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.text.BadLocationException;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.queryParser.ParseException;
import searchPack.*;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.StringTokenizer;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.filechooser.FileFilter;
import javax.swing.table.DefaultTableModel;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.similar.MoreLikeThis;
import org.apache.lucene.util.Version;
import tools.GlobalVariables;


/**
 * The application's main frame.
 */
public class BuscadorView extends FrameView{

    public BuscadorView(SingleFrameApplication app) {
        super(app);

        initComponents();
        defaultTableModel = new javax.swing.table.DefaultTableModel(
                new Object [][] {},new String [] {"Documento", "Score"}){
                @Override
                public boolean isCellEditable(int row, int column) {
                    //all cells false
                    return false;
                }
        };
              
        resultsTable.setModel(defaultTableModel);
        resultsTable.addMouseListener(new MouseAdapter() {
            @Override
               public void mouseClicked(MouseEvent e) {
                      numRow = resultsTable.rowAtPoint(e.getPoint());
                      if (e.getClickCount() == 2) {
                        showFile(numRow);
                      }
                 }
        });
        
        totalResultsNumTF.setEditable(false);
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });

        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String)(evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer)(evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
        this.getFrame().setResizable(false);
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = BuscadorApp.getApplication().getMainFrame();
            aboutBox = new BuscadorAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        BuscadorApp.getApplication().show(aboutBox);
    }


    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        searchPanel = new javax.swing.JPanel();
        searchTextField = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        searchButton = new javax.swing.JButton();
        callAdvancedSearchButton = new javax.swing.JButton();
        indexDocsButton = new javax.swing.JButton();
        loadIndexButton = new javax.swing.JButton();
        jLabel9 = new javax.swing.JLabel();
        showResultsNumTF = new javax.swing.JTextField();
        totalResultsNumTF = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        resultsTable = new javax.swing.JTable();
        clusterButton = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jLabel11 = new javax.swing.JLabel();
        clusterComboBox = new javax.swing.JComboBox();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        indexDocsMenuItem = new javax.swing.JMenuItem();
        loadIndexMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();
        fileChooser = new javax.swing.JFileChooser();
        advancedSearchFrame = new javax.swing.JFrame();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        totalSearchTF = new javax.swing.JTextField();
        exactSearchTF = new javax.swing.JTextField();
        anyWordSearchTF = new javax.swing.JTextField();
        withoutWordsSearchTF = new javax.swing.JTextField();
        advancedSearchButton = new javax.swing.JButton();
        fieldsComboBox = new javax.swing.JComboBox();

        searchPanel.setName("searchPanel"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(buscador.BuscadorApp.class).getContext().getResourceMap(BuscadorView.class);
        searchTextField.setText(resourceMap.getString("searchTextField.text")); // NOI18N
        searchTextField.setName("searchTextField"); // NOI18N
        searchTextField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                searchTextFieldKeyPressed(evt);
            }
        });

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jLabel2.setFont(resourceMap.getFont("jLabel2.font")); // NOI18N
        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        searchButton.setText(resourceMap.getString("searchButton.text")); // NOI18N
        searchButton.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        searchButton.setName("searchButton"); // NOI18N
        searchButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchButtonActionPerformed(evt);
            }
        });

        callAdvancedSearchButton.setText(resourceMap.getString("callAdvancedSearchButton.text")); // NOI18N
        callAdvancedSearchButton.setName("callAdvancedSearchButton"); // NOI18N
        callAdvancedSearchButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                callAdvancedSearchButtonActionPerformed(evt);
            }
        });

        indexDocsButton.setText(resourceMap.getString("indexDocsButton.text")); // NOI18N
        indexDocsButton.setName("indexDocsButton"); // NOI18N
        indexDocsButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                indexDocsButtonActionPerformed(evt);
            }
        });

        loadIndexButton.setText(resourceMap.getString("loadIndexButton.text")); // NOI18N
        loadIndexButton.setName("loadIndexButton"); // NOI18N
        loadIndexButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loadIndexButtonActionPerformed(evt);
            }
        });

        jLabel9.setFont(resourceMap.getFont("jLabel9.font")); // NOI18N
        jLabel9.setText(resourceMap.getString("jLabel9.text")); // NOI18N
        jLabel9.setName("jLabel9"); // NOI18N

        showResultsNumTF.setText(resourceMap.getString("showResultsNumTF.text")); // NOI18N
        showResultsNumTF.setName("showResultsNumTF"); // NOI18N
        showResultsNumTF.setPreferredSize(new java.awt.Dimension(6, 20));

        totalResultsNumTF.setName("cantResult"); // NOI18N

        jScrollPane1.setAlignmentX(0.8F);
        jScrollPane1.setAlignmentY(0.2F);
        jScrollPane1.setName("jScrollPane1"); // NOI18N

        resultsTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Documento", "Score"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        resultsTable.setName("resultsTable"); // NOI18N
        jScrollPane1.setViewportView(resultsTable);
        resultsTable.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("resultsTable.columnModel.title0")); // NOI18N
        resultsTable.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("resultsTable.columnModel.title1")); // NOI18N

        clusterButton.setText(resourceMap.getString("clusterButton.text")); // NOI18N
        clusterButton.setName("clusterButton"); // NOI18N
        clusterButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clusterButtonActionPerformed(evt);
            }
        });

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(buscador.BuscadorApp.class).getContext().getActionMap(BuscadorView.class, this);
        jButton1.setAction(actionMap.get("MoreLikeThis")); // NOI18N
        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N

        jLabel11.setFont(resourceMap.getFont("jLabel11.font")); // NOI18N
        jLabel11.setText(resourceMap.getString("jLabel11.text")); // NOI18N
        jLabel11.setName("jLabel11"); // NOI18N

        clusterComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "contenido", "titulo", "anio" }));
        clusterComboBox.setName("clusterComboBox"); // NOI18N

        javax.swing.GroupLayout searchPanelLayout = new javax.swing.GroupLayout(searchPanel);
        searchPanel.setLayout(searchPanelLayout);
        searchPanelLayout.setHorizontalGroup(
            searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, searchPanelLayout.createSequentialGroup()
                .addGroup(searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(searchPanelLayout.createSequentialGroup()
                        .addGap(19, 19, 19)
                        .addGroup(searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(searchPanelLayout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(searchTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 436, Short.MAX_VALUE)
                                .addGap(20, 20, 20)
                                .addComponent(searchButton)
                                .addGap(10, 10, 10))
                            .addGroup(searchPanelLayout.createSequentialGroup()
                                .addGroup(searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel9)
                                    .addComponent(jLabel2))
                                .addGap(24, 24, 24)
                                .addGroup(searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(totalResultsNumTF, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(searchPanelLayout.createSequentialGroup()
                                        .addComponent(showResultsNumTF, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(25, 25, 25)
                                        .addComponent(jLabel11)))
                                .addGap(6, 6, 6))))
                    .addGroup(searchPanelLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 589, Short.MAX_VALUE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 232, Short.MAX_VALUE)
                    .addComponent(indexDocsButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 232, Short.MAX_VALUE)
                    .addComponent(callAdvancedSearchButton, javax.swing.GroupLayout.DEFAULT_SIZE, 232, Short.MAX_VALUE)
                    .addGroup(searchPanelLayout.createSequentialGroup()
                        .addComponent(clusterComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(clusterButton, javax.swing.GroupLayout.DEFAULT_SIZE, 114, Short.MAX_VALUE))
                    .addComponent(loadIndexButton, javax.swing.GroupLayout.DEFAULT_SIZE, 232, Short.MAX_VALUE))
                .addContainerGap())
        );
        searchPanelLayout.setVerticalGroup(
            searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(searchPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(searchTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(callAdvancedSearchButton)
                    .addComponent(searchButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel9)
                    .addComponent(showResultsNumTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(clusterComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(clusterButton)
                    .addComponent(jLabel11))
                .addGap(13, 13, 13)
                .addGroup(searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(totalResultsNumTF, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addGap(8, 8, 8)
                .addGroup(searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(searchPanelLayout.createSequentialGroup()
                        .addComponent(indexDocsButton)
                        .addGap(18, 18, 18)
                        .addComponent(loadIndexButton)
                        .addGap(18, 18, 18)
                        .addComponent(jButton1))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 397, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        indexDocsMenuItem.setText(resourceMap.getString("indexDocsMenuItem.text")); // NOI18N
        indexDocsMenuItem.setName("indexDocsMenuItem"); // NOI18N
        indexDocsMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                indexDocsMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(indexDocsMenuItem);

        loadIndexMenuItem.setText(resourceMap.getString("loadIndexMenuItem.text")); // NOI18N
        loadIndexMenuItem.setName("loadIndexMenuItem"); // NOI18N
        loadIndexMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loadIndexMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(loadIndexMenuItem);

        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 851, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 665, Short.MAX_VALUE)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3))
        );

        fileChooser.setCurrentDirectory(new java.io.File("/home/franco/H:/Facultad/Optativas/Análisis y Recuperación de Información"));
        fileChooser.setDialogTitle(resourceMap.getString("fileChooser.dialogTitle")); // NOI18N
        fileChooser.setFileSelectionMode(javax.swing.JFileChooser.FILES_AND_DIRECTORIES);
        fileChooser.setDragEnabled(true);
        fileChooser.setName("fileChooser"); // NOI18N

        advancedSearchFrame.setTitle(resourceMap.getString("advancedSearchFrame.title")); // NOI18N
        advancedSearchFrame.setMinimumSize(new java.awt.Dimension(530, 320));
        advancedSearchFrame.setName("advancedSearchFrame"); // NOI18N
        advancedSearchFrame.setResizable(false);

        jLabel3.setFont(resourceMap.getFont("jLabel3.font")); // NOI18N
        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
        jLabel5.setName("jLabel5"); // NOI18N

        jLabel6.setText(resourceMap.getString("jLabel6.text")); // NOI18N
        jLabel6.setName("jLabel6"); // NOI18N

        jLabel7.setText(resourceMap.getString("jLabel7.text")); // NOI18N
        jLabel7.setName("jLabel7"); // NOI18N

        jLabel8.setText(resourceMap.getString("jLabel8.text")); // NOI18N
        jLabel8.setName("jLabel8"); // NOI18N

        totalSearchTF.setText(resourceMap.getString("totalSearchTF.text")); // NOI18N
        totalSearchTF.setName("totalSearchTF"); // NOI18N
        totalSearchTF.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                totalSearchTFKeyPressed(evt);
            }
        });

        exactSearchTF.setText(resourceMap.getString("exactSearchTF.text")); // NOI18N
        exactSearchTF.setName("exactSearchTF"); // NOI18N
        exactSearchTF.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                exactSearchTFKeyPressed(evt);
            }
        });

        anyWordSearchTF.setText(resourceMap.getString("anyWordSearchTF.text")); // NOI18N
        anyWordSearchTF.setName("anyWordSearchTF"); // NOI18N
        anyWordSearchTF.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                anyWordSearchTFKeyPressed(evt);
            }
        });

        withoutWordsSearchTF.setText(resourceMap.getString("withoutWordsSearchTF.text")); // NOI18N
        withoutWordsSearchTF.setName("withoutWordsSearchTF"); // NOI18N
        withoutWordsSearchTF.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                withoutWordsSearchTFKeyPressed(evt);
            }
        });

        advancedSearchButton.setText(resourceMap.getString("advancedSearchButton.text")); // NOI18N
        advancedSearchButton.setName("advancedSearchButton"); // NOI18N
        advancedSearchButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                advancedSearchButtonActionPerformed(evt);
            }
        });

        fieldsComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "contenido", "titulo", "direccion" }));
        fieldsComboBox.setName("fieldsComboBox"); // NOI18N

        javax.swing.GroupLayout advancedSearchFrameLayout = new javax.swing.GroupLayout(advancedSearchFrame.getContentPane());
        advancedSearchFrame.getContentPane().setLayout(advancedSearchFrameLayout);
        advancedSearchFrameLayout.setHorizontalGroup(
            advancedSearchFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(advancedSearchFrameLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(advancedSearchFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(advancedSearchFrameLayout.createSequentialGroup()
                        .addGroup(advancedSearchFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel5)
                            .addComponent(jLabel6)
                            .addComponent(jLabel7)
                            .addComponent(jLabel8))
                        .addGap(40, 40, 40)
                        .addGroup(advancedSearchFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(advancedSearchFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(exactSearchTF)
                                .addComponent(withoutWordsSearchTF, javax.swing.GroupLayout.DEFAULT_SIZE, 334, Short.MAX_VALUE)
                                .addComponent(totalSearchTF)
                                .addComponent(anyWordSearchTF))
                            .addGroup(advancedSearchFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(advancedSearchButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(fieldsComboBox, javax.swing.GroupLayout.Alignment.LEADING, 0, 129, Short.MAX_VALUE))))
                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 224, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(23, Short.MAX_VALUE))
        );
        advancedSearchFrameLayout.setVerticalGroup(
            advancedSearchFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(advancedSearchFrameLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(advancedSearchFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(totalSearchTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(advancedSearchFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(exactSearchTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(advancedSearchFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(anyWordSearchTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(advancedSearchFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(withoutWordsSearchTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(advancedSearchFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(fieldsComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(advancedSearchButton)
                .addContainerGap(21, Short.MAX_VALUE))
        );

        jLabel3.getAccessibleContext().setAccessibleName(resourceMap.getString("jLabel3.AccessibleContext.accessibleName")); // NOI18N

        setComponent(searchPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents

        
    private void indexDocsMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_indexDocsMenuItemActionPerformed
        try {
            indexFiles();
        } catch (IOException ex) {
            Logger.getLogger(BuscadorView.class.getName()).log(Level.SEVERE, null, ex);
             String message1 = "El proceso de indexado fallo por un error de entrada/salida.\nMirar log para mas informacion";
              JOptionPane.showMessageDialog(new JFrame(), message1, "Dialog",
              JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_indexDocsMenuItemActionPerformed

    private void callAdvancedSearchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_callAdvancedSearchButtonActionPerformed
        advancedSearchFrame.setVisible(true);
        advancedSearchFrame.setLocationRelativeTo(this.searchPanel);
    }//GEN-LAST:event_callAdvancedSearchButtonActionPerformed

    private void indexDocsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_indexDocsButtonActionPerformed
        try {
            indexFiles();
        } catch (IOException ex) {
            Logger.getLogger(BuscadorView.class.getName()).log(Level.SEVERE, null, ex);
        }
       
       
    }//GEN-LAST:event_indexDocsButtonActionPerformed
    
    private void loadIndexMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadIndexMenuItemActionPerformed
        try {
            loadIndex();
        } catch (CorruptIndexException ex) {
            Logger.getLogger(BuscadorView.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(BuscadorView.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_loadIndexMenuItemActionPerformed

    private void loadIndexButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadIndexButtonActionPerformed
        try {
            loadIndex();
        } catch (CorruptIndexException ex) {
            Logger.getLogger(BuscadorView.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(BuscadorView.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_loadIndexButtonActionPerformed

    private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButtonActionPerformed
        simpleSearch();
    }//GEN-LAST:event_searchButtonActionPerformed

    private void advancedSearchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_advancedSearchButtonActionPerformed
        advancedSearch();
    }//GEN-LAST:event_advancedSearchButtonActionPerformed

    private void searchTextFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_searchTextFieldKeyPressed
        if (evt.getKeyText(evt.getKeyCode()).equals("Enter")) {
           simpleSearch();
        }
    }//GEN-LAST:event_searchTextFieldKeyPressed

    private void totalSearchTFKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_totalSearchTFKeyPressed
        if (evt.getKeyText(evt.getKeyCode()).equals("Enter")) {
            advancedSearch();
        }
    }//GEN-LAST:event_totalSearchTFKeyPressed

    private void exactSearchTFKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_exactSearchTFKeyPressed
        if (evt.getKeyText(evt.getKeyCode()).equals("Enter")) {
            advancedSearch();
        }
    }//GEN-LAST:event_exactSearchTFKeyPressed

    private void anyWordSearchTFKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_anyWordSearchTFKeyPressed
        if (evt.getKeyText(evt.getKeyCode()).equals("Enter")) {
            advancedSearch();
        }
    }//GEN-LAST:event_anyWordSearchTFKeyPressed

    private void withoutWordsSearchTFKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_withoutWordsSearchTFKeyPressed
        if (evt.getKeyText(evt.getKeyCode()).equals("Enter")) {
            advancedSearch();
        }
    }//GEN-LAST:event_withoutWordsSearchTFKeyPressed

    private void clusterButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clusterButtonActionPerformed
        IndexSearcher indexSearcher = null; 
        try {
            indexSearcher = new IndexSearcher(indexDir.getDirectory(), false);
        } catch (IOException ex) {
            Logger.getLogger(BuscadorView.class.getName()).log(Level.SEVERE, null, ex);
        }
        IndexReader indexReader = indexSearcher.getIndexReader();
        MoreLikeThis mlt = new MoreLikeThis(indexReader);// = new MoreLikeThis(indexReader);
        
        if (searchManager.getTotalNumResults() > 0) {
            Thread t = new Thread(new Runnable() {
                public void run() {
                    try {
                        String clusterField = clusterComboBox.getSelectedItem().toString();
                        ArrayList<String> clusteredResults;
                        int totalResult = Integer.parseInt(totalResultsNumTF.getText());
                        int totalShow = Integer.parseInt(showResultsNumTF.getText());
                        int max = 0;
                         if (totalResult<totalShow) {
                              max = totalResult;
                        }
                         else
                             max = totalShow;
                        clusteredResults = searchManager.clusterResults(clusterField,max);
                        loadResults(clusteredResults);
                        stopShowingLoading("Todos los resultados se clasificaron exitosamente");
                    } catch (BadLocationException ex) {
                        Logger.getLogger(BuscadorView.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (IOException ex) {
                        Logger.getLogger(BuscadorView.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (Exception ex) {
                        Logger.getLogger(BuscadorView.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            });
            showLoading("Clasificando resultados...por favor esperar...");
            t.start();
        }
        else {
            JOptionPane.showMessageDialog(new JFrame(), "Se debe realizar una busqueda antes de clasificar los resultados.", "Accion Invalida", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_clusterButtonActionPerformed

    private void simpleSearch() {
        String textToFind;
        marcarTodas = searchTextField.getText();
        marcarAlgunas = "";
        marcarExacta = "";

        try {
            textToFind = searchManager.createQuery(marcarTodas, "", "", "");
            findFiles(textToFind);
        } catch (CorruptIndexException ex) {
            Logger.getLogger(BuscadorView.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(BuscadorView.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParseException ex) {
            Logger.getLogger(BuscadorView.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void advancedSearch() {
        String textToFind;
        marcarTodas = totalSearchTF.getText();
        marcarAlgunas =  anyWordSearchTF.getText();
        marcarExacta = exactSearchTF.getText();

        try {
            textToFind = searchManager.createQuery(marcarTodas,marcarExacta ,marcarAlgunas, withoutWordsSearchTF.getText());
            findFiles(textToFind);
        } catch (CorruptIndexException ex) {
            Logger.getLogger(BuscadorView.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(BuscadorView.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParseException ex) {
            Logger.getLogger(BuscadorView.class.getName()).log(Level.SEVERE, null, ex);
        }
        advancedSearchFrame.setVisible(false);
    }

    private void showFile(int row) {
        StringTokenizer tokensT = null;
        StringTokenizer tokensA = null;
        StringTokenizer tokensE = null;
        if(!"".equals(marcarTodas)){
            tokensT = new StringTokenizer(marcarTodas);
        }            
        if(!"".equals(marcarAlgunas)){
            tokensA = new StringTokenizer(marcarAlgunas);
        }
        if(!"".equals(marcarExacta)){
            tokensE = new StringTokenizer(marcarExacta);
        }
        
        String archivoPath = (String) defaultTableModel.getValueAt(row,0);
        
        JFrame ventana = new JFrame();
        
        PruebaEditorHtml.getInstance().creaTodo(searchManager,ventana.getContentPane(),archivoPath,tokensT,tokensA,tokensE);
        ventana.pack();
        ventana.setVisible(true);
    }

    private void loadResults(ArrayList<String> results) throws CorruptIndexException, IOException {
        cleanDefaultTableModel();
        for (int i=0; i<results.size(); i=i+2) {
             defaultTableModel.insertRow(resultsTable.getRowCount(),
                                         new Object[] {results.get(i),results.get(i+1)});
       }        
    }
    
    private void cleanDefaultTableModel() {
       int numRows = defaultTableModel.getRowCount();
       for(int i=(numRows - 1); i>=0; i--) {
           defaultTableModel.removeRow(i);
       }
    }
   
    private void showLoading(String text) {
         fr = new JFrame();
         c = new cargando(text);
         fr.add(c);
         fr.setVisible(true);
         fr.setLocationRelativeTo(searchTextField);
         fr.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);         
         fr.pack();
         fr.setContentPane(c);
         fr.setResizable(false);
         fr.setTitle("Loading...");                  
    }
    
    private void stopShowingLoading(String message){
        fr.setVisible(false);
        fr.dispose();    
        JOptionPane.showMessageDialog(this.getComponent(), message);
    }
  
    private int openFile() {
        fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
        fileChooser.setDialogTitle("Elegir los archivos a indexar");
        fileChooser.setFileFilter(new HTMLFileFilter());
        return fileChooser.showOpenDialog(this.getFrame());
    }

    private int saveFile() {
        fileChooser.setDialogTitle("Elegir donde guardar el indice");
        fileChooser.setDialogType(JFileChooser.SAVE_DIALOG);             
        return fileChooser.showSaveDialog(this.getFrame());
    }

    private String getDialogMessage(File elementChoosed){
        File[] files = null;
        String message = "";
         if (elementChoosed.isDirectory()) {
                files = elementChoosed.listFiles();
                message = "Los archivos en la carpeta \"" + elementChoosed.getName() + "\" fueron indexados correctamente";
            }
            else {
                files = new File[1];
                files[0] = elementChoosed;
                message = "El archivo \"" + elementChoosed.getName() + "\" fue indexado correctamente";
            }
         return message;
    }

    private void indexFiles() throws IOException {
       if (openFile() == JFileChooser.APPROVE_OPTION) {
            // Informar al usuario que el indice se esta creando
            File elementChoosed = fileChooser.getSelectedFile();
            final String message = getDialogMessage(elementChoosed);
            if (saveFile() == JFileChooser.APPROVE_OPTION) {
                 File indexFile = fileChooser.getSelectedFile();
                // Setea el lugar donde se guardara el indice
                indexDir.setDir(indexFile);
                // Setea el archivo (o directorio) que se usa para crear el indice
                dataDir.setDir(elementChoosed);
                Thread t = new Thread(new Runnable() {
                    public void run() {
                        try {
                            String fileType = "html";
                            indexManager = new IndexManager(indexDir, dataDir, analyzer, fileType);
                            ArrayList<String> notIndexed = indexManager.createIndex();
                            searchManager.createIndexSearcher(indexDir);
                                
                            if (notIndexed.isEmpty()) {  // Si todos los archivos se indexaron correctamente
                                stopShowingLoading(message);
                            }
                        } catch (BadLocationException ex) {
                            Logger.getLogger(BuscadorView.class.getName()).log(Level.SEVERE, null, ex);
                        } catch (IOException ex) {
                            Logger.getLogger(BuscadorView.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                });
                showLoading("El indice se esta creando...por favor esperar...");
                t.start();
            }
        }
    }
    
    private void loadIndex() throws CorruptIndexException, IOException {
        // Configurar "fileChooser" para abrir un indice
        fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
        fileChooser.setDialogTitle("Elegir la carpeta del indice a cargar");
        fileChooser.setFileFilter(new DirectoryFileFilter());
        int returnVal = fileChooser.showSaveDialog(this.getFrame());
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            indexDir.setDir(fileChooser.getSelectedFile());
            searchManager.closeIndex(); // Cerrar indice anterior (si lo hay)
            searchManager.createIndexSearcher(indexDir);
            JOptionPane.showMessageDialog(this.getComponent(), "Indice cargado exitosamente.");
            return;
        }      
        String message1 = "El indice no fue cargado.";
        JOptionPane.showMessageDialog(new JFrame(), message1, "Dialog", JOptionPane.ERROR_MESSAGE);
    }
    
    private void findFiles(String textToFind) throws IOException {
        int maxResultsNum = Integer.parseInt(showResultsNumTF.getText());
        ArrayList<String> searchResults = null;
        String field = fieldsComboBox.getSelectedItem().toString();
        if (searchManager.getIndex() != null) { // Si hay un indice cargado
            try {
                searchResults = searchManager.search(field, textToFind, maxResultsNum);
                
                totalHits = searchManager.getTotalNumResults();
                if (totalHits == 0) {
                    JOptionPane.showMessageDialog(c,"No se han encontrado coincidencias.");
                } else {
                    if(totalHits < maxResultsNum) {
                        maxResultsNum = totalHits;
                    }           
                }
                totalResultsNumTF.setText(String.valueOf(totalHits));
            } 
            catch (ParseException ex) {
                Logger.getLogger(BuscadorView.class.getName()).log(Level.SEVERE, null, ex);       
                JOptionPane.showMessageDialog(this.getComponent(), "Ingrese contenido para realizar la busqueda");
            } 
            catch (CorruptIndexException ex) {
                Logger.getLogger(BuscadorView.class.getName()).log(Level.SEVERE, null, ex);         
            } 
            catch (IOException ex) {
                Logger.getLogger(BuscadorView.class.getName()).log(Level.SEVERE, null, ex);          
            } 
            finally {
                loadResults(searchResults);
            }
        }
        else {  // Si no hay ningun indice cargado
           JOptionPane.showMessageDialog(this.getComponent(), "No hay un indice cargado.\nCree o cargue uno antes de realizar una busqueda.");
        }
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton advancedSearchButton;
    private javax.swing.JFrame advancedSearchFrame;
    private javax.swing.JTextField anyWordSearchTF;
    private javax.swing.JButton callAdvancedSearchButton;
    private javax.swing.JButton clusterButton;
    private javax.swing.JComboBox clusterComboBox;
    private javax.swing.JTextField exactSearchTF;
    private javax.swing.JComboBox fieldsComboBox;
    private javax.swing.JFileChooser fileChooser;
    private javax.swing.JButton indexDocsButton;
    private javax.swing.JMenuItem indexDocsMenuItem;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton loadIndexButton;
    private javax.swing.JMenuItem loadIndexMenuItem;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JTable resultsTable;
    private javax.swing.JButton searchButton;
    private javax.swing.JPanel searchPanel;
    private javax.swing.JTextField searchTextField;
    private javax.swing.JTextField showResultsNumTF;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    private javax.swing.JTextField totalResultsNumTF;
    private javax.swing.JTextField totalSearchTF;
    private javax.swing.JTextField withoutWordsSearchTF;
    // End of variables declaration//GEN-END:variables

    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;
    private IndexManager indexManager = null;
    private final Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_33);
    private final SearchManager searchManager = new SearchManager(analyzer);
    private final CustomizedDirectory indexDir = new CustomizedDirectory();
    private final CustomizedDirectory dataDir = new CustomizedDirectory();
    private ArrayList<String> resultFiles;
    private JDialog aboutBox;
    private int totalHits;
    private static JFrame fr;
    private static JPanel c;
    private DefaultTableModel defaultTableModel;
    private String marcarTodas = "";
    private String marcarAlgunas =  "";
    private String marcarExacta = "";
    private int numRow = -1;

    
    class HTMLFileFilter extends FileFilter{
        
        @Override
        public boolean accept(File f) {
            return f.isDirectory() || f.getAbsolutePath().endsWith(".html");
        }

        @Override
        public String getDescription() {
            return "HTML Files (*.html)";
        }
    }

    class DirectoryFileFilter extends FileFilter {

        @Override
        public boolean accept(File f) {
            return f.isDirectory();
        }

        @Override
        public String getDescription() {
            return "Directory";
        }

    }

 @Action
    public void MoreLikeThis() throws IOException {
        if(numRow!=-1){
        int maxResultsNum = Integer.parseInt(showResultsNumTF.getText());
        ArrayList<String> searchResults = null;
       
            String archivoPath = (String) defaultTableModel.getValueAt(numRow,0);
                searchResults = searchManager.getSimilarFiles(archivoPath,maxResultsNum);
                
                totalHits = searchManager.getTotalNumResults();
                if (totalHits == 0) {
                    JOptionPane.showMessageDialog(c,"No se han encontrado coincidencias.");
                } else {
                    if(totalHits < maxResultsNum) {
                        maxResultsNum = totalHits;
                    }           
                }
                totalResultsNumTF.setText(String.valueOf(totalHits));
             
                if (searchResults!=null)
                    loadResults(searchResults);                
           
        }
    else{
    JOptionPane.showMessageDialog(this.getComponent(),"Es necesario seleccionar un archivo de la tabla de Resultados");
}}

    
}
